using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;

namespace Sedna.Core.Security
{
    public abstract class AbstractAuthenticator : IAuthenticator
    {
        public abstract IPrincipal Authenticate(string userName, string credentials);

        public virtual void SignOut(IPrincipal principal)
        {
            UserMapper.RemoveUser();
                
            if (principal is SednaWorkPrincipal)
            {
                (principal as SednaWorkPrincipal).User = null;
            }            
        }

        # region Injecting principal

        public virtual bool InjectPrincipal()
        {
            return InjectPrincipal(UserMapper.RestoreCurrentState(), HttpContext.Current);
        }

        public virtual bool InjectPrincipal(HttpContext context)
        {
            return InjectPrincipal(UserMapper.RestoreCurrentState(), context);
        }

        public virtual bool InjectPrincipal(IPrincipal principal)
        {
            return InjectPrincipal(principal, HttpContext.Current);            
        }

        public virtual bool InjectPrincipal(IPrincipal principal, HttpContext context)
        {
            if (principal == null) 
                return false;

            Thread.CurrentPrincipal = principal;

            if (principal is SednaWorkPrincipal)
            {
                Thread.CurrentThread.CurrentCulture = (principal as SednaWorkPrincipal).Culture;
                Thread.CurrentThread.CurrentUICulture = (principal as SednaWorkPrincipal).Culture;
            }

            context.User = principal;
            
            return true;
        }

        # endregion
    }
}
